<template>
  <div class="">
    <el-form ref="tableInput" :model="tableInput" label-width="160px">
      <el-form-item label="步骤名称" prop="name">
        <el-input v-model="tableInput.name"></el-input>
      </el-form-item>
      <sql-design ref="sqlDesign" @showSQL="showSQL"></sql-design>


      <el-form-item label="SQL" prop="sql">
        <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 10}" v-model="tableInput.sql" :rows="5"></el-input>
      </el-form-item>
      <el-row type="flex">
        <el-form-item label="允许简易转换" prop="lazy_conversion_active">
          <el-checkbox v-model="tableInput.lazy_conversion_active" true-label="Y" false-label= "N"></el-checkbox>
        </el-form-item>
        <div  style="margin: 0 150px;"></div>
        <el-form-item label="替换SQL语句里的变量" prop="variables_active">
          <el-checkbox v-model="tableInput.variables_active" true-label="Y" false-label= "N"></el-checkbox>
        </el-form-item>
      </el-row>
      <el-form-item label="记录数量限制" prop="limit">
        <el-input-number v-model="tableInput.limit" controls-position="right" :min="0" title="默认为0，没有限制"></el-input-number>
      </el-form-item>
    </el-form>
    <div class="el-dialog__footer" style="margin-buttom:20px">
      <span class="dialog-footer">
        <el-button type="success" icon="el-icon-view" @click="preview" v-if="true">预览</el-button>
         <el-button
           icon="el-icon-back"
           @click="cancel">取消
        </el-button>
        <el-button
          type="primary" icon="el-icon-check"
          @click="handleSaveData()">确定
        </el-button>
      </span>
    </div>

    <!-- 表弹出框 -->
    <el-dialog
      :visible.sync="tableDialogVisible"
      :close-on-click-modal="false"
      v-el-drag-dialog
      width="40%"
      :title="tableDialogTitle"
      :append-to-body="true">
      <table-dialog ref="tableDialog" @setTable="setTable" @closeDialog="closeDialog"></table-dialog>
    </el-dialog>

    <el-dialog
      :visible.sync="previewDialogVisible"
      :close-on-click-modal="false"
       v-el-drag-dialog  custom-class="custom-dialog"
      :title="previewDialogTitle"
      :append-to-body="true">
      <preview-dialog ref="previewDialog"></preview-dialog>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="previewDialogVisible = false">确定</el-button>
        <el-button @click="previewDialogVisible = false">取消</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :visible.sync="countDialogVisible"
      :close-on-click-modal="false"
      width="40%" v-el-drag-dialog
      :title="countwDialogTitle"
      :append-to-body="true">
      输入你想预览的记录数量
      <el-input v-model="count" style="margin-top: 20px;"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确定</el-button>
        <el-button @click="countDialogVisible = false">取消</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import API from '../../../../../api/index'
import TableDialog from '../../../table/table-dialog.vue'
import PreviewDialog from '../../../preview/preview.vue'
import tableTree from '../../../table/table-tree.vue'
import * as studio from '../../../../../graph/handler/studio-handler'
import sqlDesign from './sql-design'

export default {
  name: 'TableInput',
  props: {
    name: String
  },
  components: {
    'table-dialog': TableDialog,
    'preview-dialog': PreviewDialog,
    tableTree,
    sqlDesign
  },
  watch: {
    'tableInput.connection': function (val, oldVal) {
      if (val) {
        this.$set(this, 'connectionVisible', false)
      } else {
        this.$set(this, 'connectionVisible', true)
      }
    }
  },
  data () {
    return {
      tshow: false,
      graph: null,
      dataForm: {
        srcId: '',
        srcName: '',
        selectAll: false,
        destList: []
      },
      dataRule: {
        businessName: [
          {required: true, message: '数据源不能为空', trigger: 'blur'}
        ]
      },
      srcPopover: false,
      tableDialogTitle: '浏览数据库',
      previewDialogTitle: '数据预览',
      countwDialogTitle: '输入预览记录数量',
      tableDialogVisible: false,
      previewDialogVisible: false,
      countDialogVisible: false,
      lookup: true,
      connectionVisible: true,
      count: 20,
      lookupOptions: [],
      tableInput: {
        name: '',
        sql: 'SELECT <values> FROM <table name> WHERE <conditions>',
        connection: {
          id: '',  // 数据源id
          name: '' // 数据源名称
        },
        connectionName: '', // 备用
        lazy_conversion_active: 'N', // 允许简易转换
        variables_active: 'N', // 替换SQL语句里的变量
        lookup: '',
        excute_each_row: 'N', // 执行每一行
        limit: 0 // 限制记录数量 0为不限制
      },
      temp: {
        name: '',
        sql: 'SELECT <values> FROM <table name> WHERE <conditions>',
        connection: {
          id: '',
          name: ''
        },
        connectionName: '',
        lazy_conversion_active: 'N',
        variables_active: 'N',
        lookup: '',
        excute_each_row: 'N',
        limit: 0
      },
      dbConnectionOptions: [],
      stepOptions: []
    }
  },
  methods: {
    loadData (data) {
      if (data) {
        this.tableInput = Object.assign({}, data)
        this.temp = Object.assign({}, data)
        if (this.tableInput.sqlForm) {
          this.$refs.sqlDesign.init(this.tableInput.sqlForm, this.tableInput.connection.name)
        } else {
          this.$refs.sqlDesign.initTable(this.tableInput.connection.name, this.tableInput.connection.id)
        }
      }
    },
    // 保存表单数据
    handleSaveData () {
      if (this.tableInput.name) {
        this.$emit('savePluginData', this.tableInput)
      } else {
        this.$message({
          message: '步骤名称必填',
          type: 'warning'
        })
      }
    },
    cancel () {
      if (this.temp) {
        this.saveTempPluginData(this.temp)
      } else {
        let tempdata = JSON.parse(JSON.stringify(this.temp))
        tempdata['name'] = this.tableInput.name
        this.saveTempPluginData(tempdata)
      }
      this.$emit('cancel')
    },
    setGraph (val) {
      this.graph = val
    },
     // 重置表单数据
    resetFormData (stepname) {
      this.$forceUpdate()
      this.$refs['tableInput'].resetFields()
      this.tableInput.name = stepname
    },
    saveTempPluginData (formData) {
      this.$emit('saveTempPluginData', formData)
    },
    // 获取数据源
    databases () {
      API.repository.databases().then(res => {
        this.dbConnectionOptions = res.data
      }).catch(error => {
        const errorResultData = error.response.data
        this.$message({
          message: errorResultData.error.message,
          type: 'warning'
        })
      })
    },
    // 获取SQL语句
    getSql () {
      this.tableDialogVisible = true
      if (this.tableInput.connection) {
        API.database.explorer({'database': this.tableInput.connection}).then(res => {
          this.$refs.tableDialog.data = res.data
        }).catch(error => {
          const errorResultData = error.response.data
          this.$message({
            message: errorResultData.error.message,
            type: 'warning'
          })
        })
      }
    },
    setTable (currentData) {
      const param = {}
      param['database'] = this.tableInput.connection
      param['schema'] = currentData.schema
      param['table'] = currentData.name
      this.$confirm('你想在SQL包含字段名吗?', '问题?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      }).then(() => {
        const that = this
        param['includeField'] = true
        API.database.getSQL(param).then(res => {
          that.$set(this.tableInput, 'sql', res.data)
        }).catch(error => {
          const errorResultData = error.response.data
          this.$message({
            message: errorResultData.error.message,
            type: 'warning'
          })
        })
      }).catch(() => {
        const that = this
        param['includeField'] = false
        API.database.getSQL(param).then(res => {
          that.$set(this.tableInput, 'sql', res.data)
        }).catch(error => {
          const errorResultData = error.response.data
          this.$message({
            message: errorResultData.error.message,
            type: 'warning'
          })
        })
      })
    },
    closeDialog () {
      this.tableDialogVisible = false
    },
    preview () {
      this.countDialogVisible = true
    },
    handleSubmit () {
      this.countDialogVisible = false
      this.previewDialogVisible = true
      this.$nextTick(() => {
        this.$emit('savePluginData', this.tableInput, true)
        const xml = studio.getMxGraphXml(this.graph)
        this.$refs.previewDialog.loadData({'stepName': this.tableInput.name, 'rowLimit': this.count}, xml)
      })
    },
    /****
     * 数据源选中
     * @param data
     * @param node
     */
    srcSelectHandler (data, node) {
      let connection = {
        id: data.id,
        name: data.name
      }
      this.tableInput.connection = connection
    },
    /***
     * 表选中
     * @param data
     * @param node
     */
    tableSelectHandler (data, node) {
      let connection = {
        id: node.parent.data.id,
        name: node.parent.data.name
      }
      this.tableInput.connection = connection
      this.tableInput.name = data.name
      let datasourceId = data.parentId
      let tableName = data.name
      let schemaName = ''
      const that = this
      const id = data.id
      API.srcAPI.getInfo(data.parentId).then(({data}) => {
        if (data && data.code === 0) {
          if (data.entity && data.entity.dbSchema) {
            schemaName = data.entity.dbSchema
          }
          API.tableAPI.getTableFields(id).then(({data}) => {
            if (data && data.code === 0) {
              if (data.list.length > 0) {
                let filelds = []
                data.list.forEach(element => {
                  filelds.push(element.fieldCode)
                })
                let params = {
                  database: datasourceId,
                  table: tableName,
                  schema: schemaName,
                  columns: filelds.join(',')
                }
                API.database.getSQL15s(params).then(res => {
                  that.$set(this.tableInput, 'sql', res.data)
                  this.$emit('savePluginData', this.tableInput, true)
                }).catch(error => {
                  const errorResultData = error.response.data
                  that.$message({
                    message: errorResultData.error.message,
                    type: 'warning'
                  })
                  that.$set(this.tableInput, 'sql', '')
                  this.$emit('savePluginData', this.tableInput, true)
                })
              }
            }
          })
        }
      })
      this.srcPopover = false
    },
    // 通过sql-design获取sql
    showSQL (sql, form) {
      this.tableInput.sql = sql
      this.tableInput.sqlForm = form
      this.tableInput.connection = {
        id: form.src,
        name: form.srcName
      }
    },
    init () {
      this.visible = true
      this.selectAll = false
    },
    editDb () {
    },
    newDb () {}
  },
  mounted () {
    this.init()
  }
}
</script>

